package com.wavehi.homework.fourth;

import com.wavehi.pojo.Person;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @Author WaveHi
 * @Date 25/8/2021 下午 8:09
 * @Version 1.0
 * @Contact HJBWaveHi@163.com
 * @Description Fourth homework : Call methods.
 */
public class ReflectionDemo4 {

    /**
     * 动态调用Person类的方法
     * @param name 方法名
     * @param params 方法参数
     * @return 方法运行的结果
     */
    public Object CallMethod(String name,Object... params) {

        //获取Class对象
        Class<Person> personClass = Person.class;
        Class<?>[] classes = null;
        if(params != null) {
            classes = new Class[params.length];
            for(int i = 0;i < params.length;i++) {

                classes[i] = params[i].getClass();

            }
        }
        try {
            //获取方法
            Method declaredMethod = personClass.getDeclaredMethod(name,classes);
            declaredMethod.setAccessible(true);

            //调用并返回结果
            return declaredMethod.invoke(personClass.newInstance(),params);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("Error!");
        }

    }

}

//小结：在调用private的方法前应设置方法对象的accessiable的属性为true